package com.lamda.zhekou.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lamda.zhekou.constraints.Configuration;
import com.lamda.zhekou.exception.ZheKouException;
import com.lamda.zhekou.master.event.DataEvent;
import com.lamda.zhekou.master.event.DataListener;
import com.lamda.zhekou.master.session.WorkerSessionScheduler;
import com.lamda.zhekou.model.ServerHost;
import com.lamda.zhekou.model.VPS;
import io.netty.channel.Channel;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;

/**
 * Created by MJiao on 15/8/27.
 */
@Component
public class WorkerManager {

    private static Logger LOGGER = Logger.getLogger(WorkerManager.class);

    @Autowired
    private WorkerSessionScheduler workerSessionScheduler;

    @Autowired
    private ServerHostManager serverHostManager;

    public WorkerManager(){

    }

    public void ready(){
        this.workerSessionScheduler.on(Configuration.Route.REGISTER, new DataListener() {
            @Override
            public void receiveData(DataEvent event, Channel channel) {
                LOGGER.info("收到vps的注册信息:" + event.getMessage());


                JSONObject jsonObject = event.getMessage().getJSONObject("msg");
                ServerHost serverHost = new ServerHost();
                serverHost.setIp(jsonObject.getString("hostIp"));
                serverHost.setHostname(jsonObject.getString("hostname"));

                serverHost.setRemark(jsonObject.getString("remark"));
                serverHost.setCreateTime(new Timestamp(System.currentTimeMillis()));
                List<VPS> vpsList = JSON.parseArray(jsonObject.getJSONArray("vpsList").toJSONString(), VPS.class) ;
                serverHost.setVpsSet(new HashSet<VPS>(vpsList));
                try {
                    serverHostManager.registerServerHost(serverHost);

                } catch (ZheKouException e) {
                    e.printStackTrace();
                }
                WorkerManager.this.workerSessionScheduler.checkOrRegisterWorkSession(channel,jsonObject.getString("hostIp"));
            }

        });
        this.workerSessionScheduler.on(Configuration.Route.HEARTBEAT, new DataListener() {
            @Override
            public void receiveData(DataEvent event, Channel channel) {

            }

        });
    }

}
